<?php
/**
 * Created by PhpStorm.
 * User: 陈艺赫
 * Date: 2018/5/4
 * Time: 0:42
 */

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;
use app\user\model\User;

class Login extends Controller
{
    public function index()
    {
        if (User::isLogin()) {
            $this->redirect('Index/index');
            exit();
        } else {
            return view();
        }
    }

    public function LoginPost()
    {
        if ($this->request->isPost()) {
            $uname = input('post.uname');
            $pwd = input('post.pwd');
            $captcha = input('post.captcha');
            $error = '';
            $success = User::userLogin($uname, $pwd, $captcha, $error);
            if ($success) {
                $this->success('success');
            } else {
                $this->error($error);
            }
        }
    }

    public function logout()
    {
        Session::clear();
        $this->redirect('Login/index');
    }

    /*
       * 首次修改密码
       * */
    public function showFirstChangePwd(){
        $id = session('id');
        $user = new User();
        $user_info = $user->find($id)->toArray();
        $this->assign('info', $user_info);
        return view();
    }
    /*
     * 首次修改密码提交
     * */
    public function firstEditPwdPost(){
        $id = input('post.id');
        $old_pwd = input('old_pwd');
        $new_pwd = input('new_pwd');
        $user = Db::name('user')->find($id);
        // 校验密码
        $password = $old_pwd . $user['salt'] . config('password');
        $password = md5(md5($password));
        $hash = $user['pwd'];
        if ($password !== $hash) {
            $error = '密码错误，请重新输入！';
            $this->error($error);
        }else{
            $temp = User::makePasswordAndSalt($new_pwd);
            $user['pwd'] = $temp['password'];
            $user['salt'] = $temp['salt'];
            Db::name('user')->update($user);
            session('last_login_time',$user['last_login_time']);
            $this->success('密码修改成功');
        }
    }
}